#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import re
import time, os
from appium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import win32api
import win32con
from lib.Logger.LoggerBase import log
import pyautogui
from PIL import Image, ImageChops
from functools import reduce
import operator
import allure


class winApp():

    def __init__(self, desired_caps=None, host="localhost", port="4723"):
        # 打开WinAppDriver服务
        # 注意：如果手动开启，则可以注释掉
        # os.system(r'start "" /d "C:\Program Files (x86)\Windows Application Driver\"  "WinAppDriver.exe"')

        # 配置信息, 包含：平台名、系统、应用程序绝对路径
        if desired_caps == None:
            desired_caps = {'platformName': 'Windows', 'deviceName': 'WindowsPC',
                            'app': r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe"}
        # app 也可以直接写Root
        # 连接WinAppDriver服务，打开目标软件
        self.driver = webdriver.Remote('http://{}:{}'.format(host, port), desired_caps)
        self.log = log
        print("service start")

    def check_element_attribute(self, element, attribute, check):
        pass

    def send_msg(self, element_name, msg):
        """
        :param element_name:元素name值
        :param msg:
        :return:
        """
        # 通过name属性，找到目标元素
        chat_element = self.driver.find_element_by_name(element_name)
        # 点击元素，进入聊天界面
        chat_element.click()
        # 找到输入框，并输入
        self.driver.find_element_by_name("输入").send_keys(msg)
        # 点击右下角的发送，发送消息出去
        self.driver.find_element_by_name("sendBtn").click()

    def action_move(self):
        # 模拟屏幕滑动
        # 1、移动到某个元素区域
        ActionChains(self.driver).move_to_element(
            self.driver.find_element_by_name("element_name")).perform()
        # 2、滑动界面
        # 比如，向上滚动，模拟滑动
        win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, 0, 0, -500)

    def picture_assert(self, expect_pic, fact_pic, differ_num=0.0):
        """
        图片断言
        """
        expect = Image.open(expect_pic)
        fact = Image.open(fact_pic)
        histogram1 = expect.histogram()
        histogram2 = fact.histogram()
        differ = math.sqrt(
            reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, histogram1, histogram2))) / len(histogram1))

        def report(differ, differ_num):
            different = ImageChops.difference(expect, fact)
            differ_path = re.sub("\w+\.jpg", "differ.jpg", fact_pic)
            different.save(differ_path)
            with open(expect_pic, mode="rb") as f1, open(fact_pic, mode="rb") as f2, open(differ_path, mode="rb") as f3:
                string001 = "图片不一致！！！要求：{}，实际值：{} ".format(differ_num, differ)
                with allure.step(string001):
                    allure.attach(f1.read(), "expect_pic", allure.attachment_type.PNG)
                    allure.attach(f2.read(), "fact_pic", allure.attachment_type.PNG)
                    allure.attach(f2.read(), "differ_pic", allure.attachment_type.PNG)
            return differ, differ_num

        # 容差比较
        assert differ <= differ_num, report(differ, differ_num)
        return differ

    def tearDownFunc(self):
        log.info("准备退出")
        # 1、释放资源
        self.driver.quit()
        # 2、关闭应用程序
        os.system(' @taskkill /f /im xxxx.exe')

# if __name__ == "__main__":
#     app = winApp()
#     app.open_app(host="127.0.0.1", port="4723")
#     app.send_msg(element_name="黑娃", msg="123321")
#     app.tearDownFunc()
